package BasicClass.Four;

public class Test_Seven {
    public static void main(String[] args) {
        ListNode node = new  ListNode(1);
        ListNode node1 = new ListNode(2);
        ListNode node2 = new ListNode(3);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(2);
        ListNode node5 = new ListNode(1);

        node.next = node1;
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;

        System.out.println(isPail(node));
    }

    /**
     * 给定一个链表，请判断该链表是否为回文结构。
     * @param head
     * @return
     */
    public static boolean isPail (ListNode head) {//额外空间O（1）,时间复杂度O（logN）
        ListNode fastNode = head;
        ListNode lastNode = head;
        while (fastNode.next!=null && fastNode.next.next!=null){//找到中间节点
            fastNode = fastNode.next.next;
            lastNode = lastNode.next;
        }
        ListNode reverseList = ReverseList(lastNode);//将中间节点连带后面节点进行反转
        ListNode pre = reverseList;
        while (head!=null && head.val == reverseList.val){//将反转后的节点与前半截进行比较判断
            head = head.next;
            reverseList = reverseList.next;
        }
        boolean flag = (head == null);
        ListNode list = ReverseList(pre);//将反转后的后半截链表反转回去
        while (list!=null){
            System.out.print(list.val+"-->");
            list = list.next;
        }
        return flag;
    }

    public static ListNode ReverseList(ListNode head) {
        ListNode pre = null;
        ListNode cru = null;
        while (head!=null){
            cru = head.next;
            head.next = pre;
            pre = head;
            head = cru;
        }
        return pre;
    }

    public static class ListNode {
        int val;
        ListNode next = null;

        ListNode(int val) {
            this.val = val;
        }
    }
}
